<?php
	include 'common.php';
	
	// String -> Boolean
	// Checks if the file associated with the user exists. If it does then
	// it returns the SHA256 code to compare to the entered password.
	// Otherwise it returns false.
	function userExists($username){
		// Only proceeds if the function returns a non-empty string of
		// information.
		return file_exists("../user-accounts/$username" . ".txt");
	}
	
	// String -> Boolean
	// Returns whether or not the passwords match.
	function hashMatch($username){
		// gets the sha256 hash
		// the hash is the 0th element
		$array = file("../user-accounts/$username" . ".txt");
		return trim($array[0])===hash("sha256", $_SESSION['pwd']);
	}
	
	// void -> string or exit()
	// Returns a user name if the user exists, otherwise exits the function
	function checkAuthentication() {
		if(!isset($_REQUEST['user']) && !isset($_SESSION['user'])){
			header('Location: index.php');
			exit();
		}
		
		//Data sent from index.php that is stored into session variables
		if($_SESSION['user'] == NULL){
			$_SESSION['user'] = untaint($_REQUEST["user"]);
			$_SESSION['pwd'] = $_REQUEST["pwd"];
		}
		$user=$_SESSION['user'];
		
		if(!(userExists($_SESSION['user']) && hashMatch($_SESSION['user']))){
			// redirects to index because of wrong username/password
			header('Location: index.php');
			exit();
		} 
		
		return $user;
    }
	
	// setAccount: string, string, string, string -> text file/user account
	// creates or overwrites a user account (overwriting is for resting the password)
	function setAccount($user, $pass, $auth, $email){
		// FILENAME: username.text
		// LINE 0: password hash
		// LINE 1: authorization level
		// LINE 2: e-mail address (for reseting password)
		
		$filepath = "../user-accounts/$user.txt";
		file_put_contents($filepath, hash("sha256", $pass));
		file_put_contents($filepath, "\n$auth", FILE_APPEND);
		file_put_contents($filepath, "\n$email", FILE_APPEND);
	}
	
	// getUserEmail: string -> string
	// returns the e-mail associated with the user
	function getUserEmail($username){
		$array = file("../user-accounts/$username" . ".txt");
		return trim($array[2]);
	}
	
	// String -> String
	// Returns the permissions of the user
	// The permissions are: lab manager, lab inspector, and lab auditor
	//						(labman)	 (labins)			(labaud)
	function getPermissions($username){
		// gets the permissions for the associated user
		// the permissions is stored in the 1st element
		$array = file("../user-accounts/$username" . ".txt");
		return trim($array[1]);
	}
	
	// getPassword : String -> String
	// Returns the hash of the password for the specified user
	function getPassword($username){
		$array = file("../user-accounts/$username" . ".txt");
		return trim($array[0]);
	}
?>